var isSubmit = 0;// 0 可以提交，1 不可提交
function editPic(imgSort, isadd) {
    sessionStorage.setItem("isadd",isadd);
    sessionStorage.setItem("imgSort",imgSort);
    layer_show("修改图片","spuPic.html","1000","800");
}
function addPic(imgSort, isadd) {
    sessionStorage.setItem("isadd",isadd);
    sessionStorage.setItem("imgSort",imgSort);
    layer_show("添加图片","spuPic.html","1000","800");
}
function deletePic(imgSort) {
    var popId = layer.confirm('确认要删除吗？',function(index){
        $(".addSpuImgbox").css({
            display:"block"
        })
        var spuImgCache = JSON.parse(sessionStorage.getItem("spuImgCache"));
        var spuInfoImgArr = Object.keys(spuImgCache);
        if(sessionStorage.getItem("spuImgCache")){
            for (var i = 0; i < spuInfoImgArr.length; i++) {
                if(imgSort == (i + 1)){
                    for (var j = imgSort; j < spuInfoImgArr.length; j++) {
                        spuImgCache["img" + (j + 1)].imgSort = j;
                        spuImgCache["img" + j] = spuImgCache["img" + (j + 1)];
                    }
                    delete spuImgCache["img" + spuInfoImgArr.length];
                    break;
                }
            }
            sessionStorage.setItem("spuImgCache",JSON.stringify(spuImgCache));
        }
        //var index = parent.layer.getFrameIndex(popId);
        layer.close(popId);
        addSpuPic();
    });
}

function isNull () {
    if ($("#goodsName").val() == "") {
        console.log(111);
        $("#goodsName").css({
            border: "1px red solid"
        });
        $(".errorMsg").css({
            display:"inline"
        });
    }else{
        $("#goodsName").css({
            border: "1px #ddd solid"
        });
        $(".errorMsg").css({
            display:"none"
        });
    }
}

function addAttr(attrId,checkedIds) {
    layer_show("属性值添加","addNature.html","600","400");
    sessionStorage.setItem("atrrId",attrId);
    sessionStorage.setItem("checkedIds",checkedIds);
    sessionStorage.setItem("spuOrSkuStatus","spu");
}

function makeSure() {
    var spuResult = JSON.parse(sessionStorage.getItem("spuInfo"));

    var saleStatus = spuResult.spu.sale_status;
    // 获取客户类型
    var customerType = $("input:checkbox[name='customerType']:checked").map(function(index,elem) {
        return $(elem).val();
    }).get().join(',');

    // 当全选的时候长度为三，则客户类型为3
    if(customerType.length == 3 ){
        customerType = 3;
    }

    if(customerType.length == 0 ){
        customerType = 0;
    }

    // 销售区域
    var saleMsg = $('input[name="saleArea"]:checked').val();

    if(saleStatus == 1 && customerType == 0 ){
        $.Huimodalalert("客户类型可见为空，请选择", 2000);
        return false;
    }
    if (isSubmit != 0) {
        $.Huimodalalert("排序输入有误", 2000);
        return false;
    }
    var imgSort = document.getElementsByName("imgSort");
    var sort = 0;
    var sortSum = 0;
    for (var i = 0; i < imgSort.length; i++) {
        sort += Number(imgSort[i].value);
        sortSum += i + 1;
    }
    if (sort != sortSum) {
        $.Huimodalalert("排序顺序输入有误", 2000);
        console.log("排序顺序输入有误");
        return false;

    }

    if($("#brandId").html() == null || $("#brandId").html() == '' || $("#brandId").html() == "undefined"){
        $.Huimodalalert("请输入品牌", 2000);
        return false;
    }

    console.log("排序顺序无误")
    if ($("#goodsName").val() == "") {
        $("#goodsName").css({
            border: "1px red solid"
        });
        $(".errorMsg").css({
            display:"inline"
        });
    }else if($("#brandName").html() == ""){
        $(".brandErrorMsg").css({
            display:"inline"
        });
    }else if ($("#subtitile").val().length > 100){
        $.Huimodalalert('商品副标题超出字符限制',2000);
        $("#subtitile").css({
            border: "1px red solid"
        });
        $(".subtitileErrorMsg").css({
            display:"inline"
        });
    } else {
        $("#subtitile").css({
            border: "1px #ddd solid"
        });
        $("#goodsName").css({
            border: "1px #ddd solid"
        });
        $(".subtitileErrorMsg").css({
            display:"none"
        });
        $(".errorMsg").css({
            display:"none"
        });
        $(".brandErrorMsg").css({
            display:"none"
        });

        if(sessionStorage.getItem("attrObjCanch")){
            var attrObjCanch = JSON.parse(sessionStorage.getItem("attrObjCanch"));
            var  attValList = []
            for(var i=0;i<attrObjCanch.length;i++){
                attValList.push({"attributeId": attrObjCanch[i].attribute_id, "attriValueIds": []})
                for(var j=0;j<attrObjCanch[i].value.length;j++){
                    attValList[i].attriValueIds.push(attrObjCanch[i].value[j].attri_value_id);
                }
            }
        }else {
            var attrObjCanch = spuResult.attribute;
            var  attValList = []
            for(var i=0;i<attrObjCanch.length;i++){
                attValList.push({"attributeId": attrObjCanch[i].attribute_id, "attriValueIds": []})
                for(var j=0;j<attrObjCanch[i].value.length;j++){
                    attValList[i].attriValueIds.push(attrObjCanch[i].value[j].attri_value_id);
                }
            }
        }

        var spuImgs = [];
        var imgLength= document.getElementsByClassName("imgboxUl")[0].children.length;
        console.log(imgLength);
        for (var i = 1; i <= imgLength; i++) {
            if($("#spuImg" + i).children().length != 0){
                spuImgs.push( {
                    "imgId": $("#spuImgId" + i).html(),
                    "imgSort": $("#spuImgSort" + i).val(),
                    "imgUrl": $("#spuImgUrl" + i).html().split("?")[0],
                    "spuCode": $("#spu_code").html()
                })
            }
        }
        console.log(spuImgs);
        var aliasArr = [];
        var another_name = document.querySelectorAll(".another_name");
        var localStorageParameters = decodeURIComponent(web.readCookie("loginData"));
        var JsonObject =JSON.parse(localStorageParameters);
        for(var i=0;i<another_name.length;i++){
            if(another_name[i].value !== ""){
                var index = $.inArray(another_name[i].value,aliasArr);
                if(index >= 0){
                    $.Huimodalalert('商品别名"'+another_name[i].value +'"重复',2000);
                    return false;
                }else{
                    aliasArr.push(another_name[i].value);
                }
            }
        }

        $.ajax({
            contentType:'application/json',
            url: root.goodsInter.goods_updateSpuDetail,
            cache: false,  //禁用缓存
            type: "POST",
            data: JSON.stringify({
                "detail": UE.getEditor('editor').getContent(),
                "brandId": $("#brandId").html(),
                "categoryid": spuResult.spu.category_id,
                "spuId": spuResult.spu.spu_id,
                "spuCode": $("#spu_code").html(),
                "subTitile": $("#subtitile").val(),
                "spuName": $("#goodsName").val(),
                "pductDetailId": spuResult.spu.procuct_detail_id,
                "alias": aliasArr,
                "attValList": attValList,
                "imgList": spuImgs,
                "lastModifiedBy":JsonObject.user.user_ID,
                "spuStandards": $("#spuStandards").val(),
                "isLimitCategory": $("#isLimitCategory").val(),
                "saleMsg": saleMsg,
                "customerType": customerType,
            }),
            success: function (data) {
                if(data.errorCode == 0){
                    layer.msg("修改成功",{icon: 6,time:1000},function () {
                        var index =  parent.location.reload();
                        parent.layer.close(index);
                    });
                }
            }
        });
    }
}

function nameAdd() {
    var aliasInp = document.querySelectorAll(".aliasInp")
    console.log(aliasInp)
    if(aliasInp.length<50){
        $("#inpBox").append('<div class="formControls col-sm-9 f-l aliasInp"><input type="text" class="input-text radius f-l another_name" value="" name="another_name" style="width: 85%"><a onclick="nameDelete(this)" class="ml-20 f-l">删除</a></div>');
    }
}
function nameDelete(nameBox) {
    /*删除别名输入框*/
    $(nameBox.parentElement).remove()
}
function selectBrand() {
    $("#selectInp").css({
        display:"block"
    });
}
/*品牌选择*/
function myFunction(){
    $.ajax({
        url: root.goodsInter.goods_getListBrand,
        cache: false,  //禁用缓存
        type: "POST",
        data: {
            brandName: $("#username").val()
        },
        success: function (data) {
            console.log(data)
            var jsonObj =data.ListBrand;
            if(jsonObj==""){
                $("#tuan").html("<li>无数据</li> ");
            }else {
                console.log(data.ListBrand)
                console.log(jsonObj.length+"!!!!!!!");
                var optionstring = "";
                for (var  i= 0; i < jsonObj.length; i++) {
                    optionstring += "<li onclick='addCodeFun("+ jsonObj[i].brandId+ ",\""+jsonObj[i].brandName+ "\")'>"+jsonObj[i].brandName+ "</li>";
                }
                $("#tuan").html(optionstring);
            }
        }
    });
}
//运营经理获取光标
$("#username").focus(function () {
    $("#tuan").show()
});
$(document).bind("click",function(e){
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#tuan").length == 0 && $(e.target).closest("#username").length == 0){
        //点击id为menu之外且id不是不是open，则触发
        $("#tuan").hide()
    }
})
var brandName = "";
var brandId = "";
function addCodeFun(id,brand_name) {
    $("#tuan").hide();
    $("#username").val(brand_name)
    brandName = brand_name;
    brandId = id;
}
function brand_sure() {
    sessionStorage.setItem("brand_name",brandName);
    sessionStorage.setItem("brand_id",brandId);
    $("#selectInp").css({
        display:"none"
    });
    addBrandName();
}
//渲染品牌名称
function addBrandName() {
    if(sessionStorage.getItem("brand_name")){
        $("#brandName").html(sessionStorage.getItem("brand_name"));
        $("#brandId").html(sessionStorage.getItem("brand_id"));
    }
}
//渲染属性名称
function addAttrName() {
    console.log(sessionStorage.getItem("attrObjCanch")+"##########");
    if(sessionStorage.getItem("attrObjCanch")){
        var attrObjCanch = JSON.parse(sessionStorage.getItem("attrObjCanch"));
        for(var i=0;i<attrObjCanch.length;i++){
            var attrValStr="";
            var attrIdsStr="";
            if(attrObjCanch[i].value.length != 0){
                for(var j=0;j<attrObjCanch[i].value.length;j++){
                    attrValStr += attrObjCanch[i].value[j].attri_value+";";
                    attrIdsStr +=attrObjCanch[i].value[j].attri_value_id+";";
                }
            }
            $("#appendAttr").remove();
            $("#attrTable").append('<tr id = "appendAttr"><th class="col-6-1 text-c">'+attrObjCanch[i].attribute_name+'</th><td><span>'+attrValStr+'</span><a onclick="addAttr('+attrObjCanch[i].attribute_id+",'"+attrIdsStr+"'"+')">添加</a></td></tr>')
        }
    }
}
//渲染图片渲染函数
function addSpuPic() {
    $(".imgTable .imgboxUl").html("");
    if(sessionStorage.getItem("spuImgCache")){
        var spuInfoImg = JSON.parse(sessionStorage.getItem("spuImgCache"));
        var spuInfoImgArr = Object.keys(spuInfoImg);
        for (var i = 0; i < spuInfoImgArr.length; i++) {
            var img = "img" + (i + 1);
            $(".imgTable .imgboxUl").append('<div class="f-l ml-5"><span id="spuImg' + (i + 1) + '" class="spu_add_img"><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + spuInfoImg[img].imgUrl + '\')" src="' + spuInfoImg[img].imgUrl + '" width="150" height="150"></span><span id="spuImgId' + (i + 1) + '" style="display: none">' + spuInfoImg[img].imgId + '</span><span id="spuImgUrl' + (i + 1) + '" style="display: none">' + spuInfoImg[img].imgUrl + '</span><div id="btnBox' + (i + 1) + '" class="pt-10 updataBtn"><a onclick="editPic(' + (i + 1) + ', false)" class="pd-20">修改</a><a onclick="deletePic(' + (i + 1) + ')" class="pd-20">删除</a></div><div class="pd-20">排序&nbsp;&nbsp;&nbsp;<input type="text" class="input-text radius" onchange="checkRepeat(this, ' + (i + 1) + ')" value="' + spuInfoImg[img].imgSort + '" id="spuImgSort' + (i + 1) + '" name="imgSort" style="width:40px"></div></div>');
        }
        /*for(item in spuInfoImg) {
            if(item.endWith("1")){
                $(".imgTable .imgboxUl").append('<div class="f-l ml-5"><span id="spuImg1" class="spu_add_img"><img onclick="picShow(\'查看图片\',\'picShow.html\',\''+spuInfoImg[item].imgUrl+'\')" src="'+spuInfoImg[item].imgUrl+'" width="150" height="150"></span><span id="spuImgId1" style="display: none">'+spuInfoImg[item].imgId+'</span><span id="spuImgUrl1" style="display: none">'+spuInfoImg[item].imgUrl+'</span><div id="btnBox1" class="pt-10 updataBtn"><a onclick="editPic(1, false)" class="pd-20">修改</a><a onclick="deletePic(1)" class="pd-20">删除</a></div><div class="pd-20">排序&nbsp;&nbsp;&nbsp;<input type="text" class="input-text radius" onchange="checkRepeat(this, 1)" value="'+spuInfoImg[item].imgSort+'" id="spuImgSort1" name="imgSort" style="width:40px"></div></div>')
            }if(item.endWith("2")){
                $(".imgTable .imgboxUl").append('<div class="f-l ml-5"><span id="spuImg2" class="spu_add_img"><img onclick="picShow(\'查看图片\',\'picShow.html\',\''+spuInfoImg[item].imgUrl+'\')" src="'+spuInfoImg[item].imgUrl+'" width="150" height="150"></span><span id="spuImgId2" style="display: none">'+spuInfoImg[item].imgId+'</span><span id="spuImgUrl2" style="display: none">'+spuInfoImg[item].imgUrl+'</span><div id="btnBox2" class="pt-10 updataBtn"><a onclick="editPic(2, false)" class="pd-20">修改</a><a onclick="deletePic(2)" class="pd-20">删除</a></div><div class="pd-20">排序&nbsp;&nbsp;&nbsp;<input type="text" class="input-text radius" onchange="checkRepeat(this, 2)" value="'+spuInfoImg[item].imgSort+'" id="spuImgSort2" name="imgSort" style="width:40px"></div></div>')
            }if(item.endWith("3")){
                $(".imgTable .imgboxUl").append('<div class="f-l ml-5"><span id="spuImg3" class="spu_add_img"><img onclick="picShow(\'查看图片\',\'picShow.html\',\''+spuInfoImg[item].imgUrl+'\')" src="'+spuInfoImg[item].imgUrl+'" width="150" height="150"></span><span id="spuImgId3" style="display: none">'+spuInfoImg[item].imgId+'</span><span id="spuImgUrl3" style="display: none">'+spuInfoImg[item].imgUrl+'</span><div id="btnBox3" class="pt-10 updataBtn"><a onclick="editPic(3, false)" class="pd-20">修改</a><a onclick="deletePic(3)" class="pd-20">删除</a></div><div class="pd-20">排序&nbsp;&nbsp;&nbsp;<input type="text" class="input-text radius" onchange="checkRepeat(this, 3)" value="'+spuInfoImg[item].imgSort+'" id="spuImgSort3" name="imgSort" style="width:40px"></div></div>')
            }if(item.endWith("4")){
                $(".imgTable .imgboxUl").append('<div class="f-l ml-5"><span id="spuImg4" class="spu_add_img"><img onclick="picShow(\'查看图片\',\'picShow.html\',\''+spuInfoImg[item].imgUrl+'\')" src="'+spuInfoImg[item].imgUrl+'" width="150" height="150"></span><span id="spuImgId4" style="display: none">'+spuInfoImg[item].imgId+'</span><span id="spuImgUrl4" style="display: none">'+spuInfoImg[item].imgUrl+'</span><div id="btnBox4" class="pt-10 updataBtn"><a onclick="editPic(4, false)" class="pd-20">修改</a><a onclick="deletePic(4)" class="pd-20">删除</a></div><div class="pd-20">排序&nbsp;&nbsp;&nbsp;<input type="text" class="input-text radius" onchange="checkRepeat(this, 4)" value="'+spuInfoImg[item].imgSort+'" id="spuImgSort4" name="imgSort" style="width:40px"></div></div>')
            }if(item.endWith("5")){
                $(".imgTable .imgboxUl").append('<div class="f-l ml-5"><span id="spuImg5" class="spu_add_img"><img onclick="picShow(\'查看图片\',\'picShow.html\',\''+spuInfoImg[item].imgUrl+'\')" src="'+spuInfoImg[item].imgUrl+'" width="150" height="150"></span><span id="spuImgId5" style="display: none">'+spuInfoImg[item].imgId+'</span><span id="spuImgUrl5" style="display: none">'+spuInfoImg[item].imgUrl+'</span><div id="btnBox5" class="pt-10 updataBtn"><a onclick="editPic(5, false)" class="pd-20">修改</a><a onclick="deletePic(5)" class="pd-20">删除</a></div><div class="pd-20">排序&nbsp;&nbsp;&nbsp;<input type="text" class="input-text radius" onchange="checkRepeat(this, 5)" value="'+spuInfoImg[item].imgSort+'" id="spuImgSort5" name="imgSort" style="width:40px"></div></div>');
                /!*$(".addSpuImgbox").css({
                    display:"none"
                })*!/
            }
        }*/
    }
}
function brand_cancel() {
    if(sessionStorage.getItem("brand_name")){
        location.replace(location.href)
        $("#selectInp").css({
            display:"none"
        });
    }else {
        sessionStorage.removeItem("brand_name");
        sessionStorage.removeItem("brand_id");
        $("#selectInp").css({
            display:"none"
        });
    }
}
/*商品图片管理-----------------------------------------------------------------------------------*/
function imgGoods_listCategory(categoryLevel) {
    var categoryName = $("#imgClass1").val();
    var user_data = {
        categoryLevel: categoryLevel,
        categoryName: $("#imgClass1").val(),
    }
    var succCallBack = function (data, status, response) {
        console.log(data)
        if (data.errorCode == "0") {
            if (data.data == null) {
                classStr = "<li>无数据</li>"
                $("#img-classUl1").html(classStr);
            } else {
                var classStr = "";
                for (var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='imgNextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
                $("#img-classUl1").html(classStr);
            }
        }
    }
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

//获取光标
$("#imgClass1").focus(function () {
    $("#img-classUl1").show();
    imgGoods_listCategory(1, 1);
});
$(document).bind("click", function (e) {
//id为menu的是菜单，id为open的是打开菜单的按钮
    if ($(e.target).closest("#img-classUl1").length == 0 && $(e.target).closest("#imgClass1").length == 0) {
//点击id为menu之外且id不是不是open，则触发
        $("#img-classUl1").hide()
    }
});
var oneCategoryId = "";
var twoCategoryId = "";
var threeCategoryId = "";
// 2,3,4级的模糊查询
function imgGetNext_input(level, category_id) {
    if (level < 4) {
        $("#imgClass" + level + "")[0].oninput = function () {
            console.log($("#imgClass" + level + "").val())
            if (level == 1) {
                oneCategoryId = category_id;
            } else if (level == 2) {
                twoCategoryId = category_id;
            } else if (level == 3) {
                threeCategoryId = category_id;
            }
            var user_data = {
                parentCateId: category_id,
                categoryName: $("#imgClass" + level + "").val()
            }
            var succCallBack = function (data, status, response) {
                console.log(data)
                if (data.errorCode == "0") {
                    if (data.data == null) {
                        classStr = "<li>无数据</li>";
                    } else {
                        var classStr = "";
                        for (var i = 0; i < data.data.length; i++) {
                            classStr += "<li onclick='imgNextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                        }
                    }
                    if (data.data[0] == undefined) {
                        classValue = category_id;
                        var nextLevel = level + 1;
                        $("#img-classUl" + nextLevel + "").html(classStr);
                        $("#img-classUl" + level + "").hide();
                    } else {
                        var nextLevel = data.data[0].category_level;
                        $("#img-classUl" + nextLevel + "").html(classStr);
                        $("#img-classUl" + level + "").show();
                    }
                }
            }
            web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
        }
//获取光标
        $("#imgClass" + level + "").focus(function () {
            $("#img-classUl" + level + "").show();
        });
        $(document).bind("click", function (e) {
//id为menu的是菜单，id为open的是打开菜单的按钮
            if ($(e.target).closest("#img-classUl" + level + "").length == 0 && $(e.target).closest("#imgClass" + level + "").length == 0) {
//点击id为menu之外且id不是不是open，则触发
                $("#img-classUl" + level + "").hide()
            }
        });
    }

}

function imgNextClass(category_id, level, category_name) {
    console.log(level)
    console.log(category_id)
    if(level == 1){
        $("#imgClass2").val("");
        $("#imgClass3").val("");
    }else if(level == 2){
        $("#imgClass3").val("");
    }
    if (level == 1) {
        oneCategoryId = category_id;
    } else if (level == 2) {
        twoCategoryId = category_id;
    } else if (level == 3) {
        threeCategoryId = category_id;
    }
    $("#imgClass" + level + "").val(category_name)
    var user_data = {
        parentCateId: category_id
    }
    var succCallBack = function (data, status, response) {
        console.log(data)
        if (data.errorCode == "0") {
            if (data.data == null) {
                classStr = "<li>无数据</li>";
            } else {
                var classStr = "";
                for (var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='imgNextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
            }
            if (data.data[0] == undefined) {
                classValue = category_id;
                var nextLevel = level + 1;
                $("#img-classUl" + nextLevel + "").html(classStr);
                $("#img-classUl" + level + "").hide();
            } else {
                var nextLevel = data.data[0].category_level;
                $("#img-classUl" + nextLevel + "").html(classStr);
                $("#img-classUl" + nextLevel + "").show();
                $("#img-classUl" + level + "").hide()
            }
        }
    }
    imgGetNext_input(level + 1, category_id);
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

var totalPage = 1;
function img_list() {

    var categoryName = $("#imgClass3").val();
    var firstCategoryName = $("#imgClass1").val();
    var secondCategoryName = $("#imgClass2").val();
    if (categoryName == "" || categoryName == undefined || categoryName == null) {
        threeCategoryId = -1;
    }

    if (firstCategoryName == "" || firstCategoryName == undefined || firstCategoryName == null) {
        oneCategoryId = -1;
    }

    if (secondCategoryName == "" || secondCategoryName == undefined || secondCategoryName == null) {
        twoCategoryId = -1;
    }

    $.ajax({
        contentType: "application/json",
        type: "POST",
        url: root.goodsInter.goods_listImg,
        cache: false,  //禁用缓存
        dataType: "json",
        data: JSON.stringify({
            "pageSize": "50",
            "nowPage": 1,
            "model": {
                "spuCode": $("#spuCode").val(),
                "skuCode": $("#skuCode").val(),
                "imgName": $("#imgName").val(),
                "oneCategoryId": oneCategoryId,
                "twoCategoryId": twoCategoryId,
                "threeCategoryId": threeCategoryId
            }
        }),
        success: function (data) {
            if (data.errorCode == 0) {
                var imgHtmlStr = "";
                var objList = data.data.list;
                if(objList != null) {
                    for(var i = 0; i < objList.length; i++) {
                        if (objList[i].img_name == null || objList[i].img_name == "null") {
                            objList[i].img_name = "";
                        }
                        if (objList[i].img_url != null && objList[i].img_url != "null") {
                            if (objList[i].use_img == 0) {
                                imgHtmlStr += '<li><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + objList[i].img_url + '\',\'500\',\'300\',\'110\')" src="' + objList[i].img_url + '"><div class="num">编码： <span>' + objList[i].img_id + '</span></div><div class="name">名称： <span>' + objList[i].img_name + '</span></div><div class="sale_pic_btn"><a onclick="updataImg(' + objList[i].img_id + ')">修改</a><a onclick="deleteImg(' + objList[i].img_id + ')">删除</a></div></li>';
                            } else if (objList[i].use_img == 1) {
                                imgHtmlStr += '<li><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + objList[i].img_url + '\',\'500\',\'300\',\'110\')" src="' + objList[i].img_url + '"><div class="num">编码： <span>' + objList[i].img_id + '</span></div><div class="name">名称： <span>' + objList[i].img_name + '</span></div><div class="sale_pic_btn"></div></li>';
                            }
                        }

                    }
                    $("#imgListBox").html(imgHtmlStr);
                }
                totalPage = data.data.totalPage
                $('.M-box3').pagination({
                    pageCount: totalPage,
                    jump: true,
                    coping: true,
                    prevContent: '上页',
                    nextContent: '下页',
                    callback: function (api) {
                        console.log(api.getCurrent());
                        $.ajax({
                            contentType: "application/json",
                            type: "POST",
                            url: root.goodsInter.goods_listImg,
                            cache: false,  //禁用缓存
                            dataType: "json",
                            data: JSON.stringify({
                                "pageSize": "50",
                                "nowPage": api.getCurrent(),
                                "model": {
                                    "spuCode": $("#spuCode").val(),
                                    "skuCode": $("#skuCode").val(),
                                    "imgName": $("#imgName").val(),
                                    "oneCategoryId": oneCategoryId,
                                    "twoCategoryId": twoCategoryId,
                                    "threeCategoryId": threeCategoryId
                                }
                            }),
                            success: function (data) {
                                console.log(data);
                                if (data.errorCode == 0) {
                                    var imgHtmlStr = "";
                                    var objList = data.data.list;
                                    if(objList != null) {
                                        for(var i = 0; i < objList.length; i++) {
                                            if (objList[i].img_name == null || objList[i].img_name == "null") {
                                                objList[i].img_name = "";
                                            }
                                            if (objList[i].img_url != null && objList[i].img_url != "null") {
                                                if (objList[i].use_img == 0) {
                                                    imgHtmlStr += '<li><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + objList[i].img_url + '\',\'500\',\'300\',\'110\')" src="' + objList[i].img_url + '"><div class="num">编码： <span>' + objList[i].img_id + '</span></div><div class="name">名称： <span>' + objList[i].img_name + '</span></div><div class="sale_pic_btn"><a onclick="updataImg(' + objList[i].img_id + ')">修改</a><a onclick="deleteImg(' + objList[i].img_id + ')">删除</a></div></li>';
                                                } else if (objList[i].use_img == 1) {
                                                    imgHtmlStr += '<li><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + objList[i].img_url + '\',\'500\',\'300\',\'110\')" src="' + objList[i].img_url + '"><div class="num">编码： <span>' + objList[i].img_id + '</span></div><div class="name">名称： <span>' + objList[i].img_name + '</span></div><div class="sale_pic_btn"></div></li>';
                                                }
                                            }

                                        }
                                        $("#imgListBox").html(imgHtmlStr);
                                    }
                                    totalPage = data.data.totalPage
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                alert(XMLHttpRequest);
                            }
                        });
                    }
                });
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}

function picShow(title, url,imgUrl) {
    window.event? window.event.cancelBubble = true : e.stopPropagation();
    sessionStorage.setItem("imgUrl",imgUrl);
    layer_show(title, url, "800", "500");
}
function addImg() {
    layer_show("增加图片", "addPic.html", "600", "400");
}

function updataImg(imgId) {
    $.ajax({
        contentType: "application/json",
        type: "POST",
        url: root.goodsInter.goods_getImg,
        cache: false,  //禁用缓存
        dataType: "json",
        data: JSON.stringify({
            "imgId": imgId
        }),
        success: function (data) {
            console.log(data);
            if (data.errorCode == 0) {
                if (data.use_img == 0) {
                    // 未使用，随便修
                    sessionStorage.setItem("imgInfo", JSON.stringify(data));
                    layer_show("修改图片", "can-updataImg.html", "600", "400");
                } else if (data.use_img == 1) {
                    //已使用，只能修改名字
                    sessionStorage.setItem("imgInfo", JSON.stringify(data));
                    layer_show("修改图片", "cannot-updataImg.html", "600", "400");
                }
            }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}

function deleteImg(imgId) {
    layer.confirm('确认要删除吗？', function (index) {
        $.ajax({
            contentType: "application/json",
            type: "POST",
            url: root.goodsInter.goods_delImg,
            cache: false,  //禁用缓存
            dataType: "json",
            data: JSON.stringify({
                "imgId": imgId
            }),
            success: function (data) {
                console.log(data);
                if(data.errorCode == 0){
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    layer.msg("删除成功",{icon: 6,time:1000},function () {
                        img_list();
                    });
                }else {
                    layer.msg(data.errorMessage,{icon: 5,time:1000},function () {
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });
    });
}

function checkRepeat(el, id) {
    isSubmit = 0;

    $(el).removeClass("error");
    /*if (el.value < 1 || el.value > 5) {
        isSubmit = 1;
        $.Huimodalalert("输入范围有误", 2000);
        console.log('输入范围有误')
        // $(el).addClass("error")
    }*/
    var imgSorts = document.getElementsByName('imgSort');
    for (var i = 0; i < imgSorts.length; i++) {
        if (i != (id-1)) {
            var obj = imgSorts[i];
            if (Number(el.value) == Number(obj.value)) {
                isSubmit = 1;
                console.log('数字重复');
                $.Huimodalalert("数字重复", 2000);
            }
        }

    }
}